<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      label-width="80px"
    >
      <el-form-item prop="username" :label="$t('user.username')">
        <el-input
          v-model="dataForm.username"
          :placeholder="$t('user.username')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="deptName" :label="$t('user.deptName')">
        <ren-dept-tree
          v-model="dataForm.deptId"
          :placeholder="$t('dept.title')"
          :dept-name.sync="dataForm.deptName"
        ></ren-dept-tree>
      </el-form-item>
      <el-form-item
        prop="password"
        :label="$t('user.password')"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.password"
          type="password"
          :placeholder="$t('user.password')"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="confirmPassword"
        :label="$t('user.confirmPassword')"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.confirmPassword"
          type="password"
          :placeholder="$t('user.confirmPassword')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="realName" :label="$t('user.realName')">
        <el-input
          v-model="dataForm.realName"
          :placeholder="$t('user.realName')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="gender" :label="$t('user.gender')">
        <ren-radio-group v-model="dataForm.gender" dict-type="gender"></ren-radio-group>
      </el-form-item>
      <el-form-item prop="email" :label="$t('user.email')">
        <el-input v-model="dataForm.email" :placeholder="$t('user.email')"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" :label="$t('user.mobile')">
        <el-input v-model="dataForm.mobile" :placeholder="$t('user.mobile')"></el-input>
      </el-form-item>
      <el-form-item prop="roleIdList" :label="$t('user.roleIdList')" class="role-list">
        <el-select
          v-model="dataForm.roleIdList"
          multiple
          :placeholder="$t('user.roleIdList')"
        >
          <el-option
            v-for="role in roleList"
            :key="role.roleIdStr"
            :label="role.name"
            :value="role.roleIdStr"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="postIdList" :label="$t('user.postIdList')" class="role-list">
        <el-select
          v-model="dataForm.postIdList"
          multiple
          :placeholder="$t('user.postIdList')"
        >
          <el-option
            v-for="post in postList"
            :key="post.id"
            :label="post.postName"
            :value="post.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="status" :label="$t('user.status')" size="mini">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">{{ $t("user.status0") }}</el-radio>
          <el-radio :label="1">{{ $t("user.status1") }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false" size="small">{{ $t("cancel") }}</el-button>
      <el-button type="primary" size="small" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce";
import { isEmail, isMobile } from "@/utils/validate";
import { decryptECB, encryptECB } from "@/utils/encryptAndDecryptUtils";
import { encrypt, decrypt } from "@/utils/sm4Utils";
export default {
  data() {
    return {
      visible: false,
      roleList: [],
      roleIdListDefault: [],
      postList: [],
      dataForm: {
        id: "",
        username: "",
        deptId: "",
        deptName: "",
        password: "",
        confirmPassword: "",
        realName: "",
        gender: 0,
        email: "",
        mobile: "",
        roleIdList: [],
        postIdList: [],
        status: 1,
        userIdStr: "",
      },
    };
  },
  computed: {
    dataRule() {
      var validatePassword = (rule, value, callback) => {
        const lengthValid = this.dataForm.password.length >= 8;
        const hasNumber = /[0-9]/.test(this.dataForm.password);
        const hasLetter = /[a-zA-Z]/.test(this.dataForm.password);
        const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(this.dataForm.password);
        const typesCount = [hasNumber, hasLetter, hasSpecialChar].filter(Boolean).length;
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        if (!lengthValid) {
          return callback(new Error("密码长度必须至少为8位"));
          // this.errorMessage = '密码长度必须至少为8位';
        }
        if (typesCount < 3) {
          return callback(new Error("密码必须由数字、字母和特殊字符3种组成"));
          // this.errorMessage = '密码必须由数字、字母或特殊字符中的3种组成';
        }
        callback();
      };
      var validateConfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t("user.validate.confirmPassword")));
        }
        callback();
      };
      var validateEmail = (rule, value, callback) => {
        if (value && !isEmail(value)) {
          return callback(
            new Error(this.$t("validate.format", { attr: this.$t("user.email") }))
          );
        }
        callback();
      };
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback(
            new Error(this.$t("validate.format", { attr: this.$t("user.mobile") }))
          );
        }
        callback();
      };
      return {
        username: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        deptName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
        confirmPassword: [{ validator: validateConfirmPassword, trigger: "blur" }],
        gender: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        realName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      };
    },
  },
  methods: {
    init() {
      this.visible = true;
      this.dataForm.deptId = "";
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields();
        this.roleIdListDefault = [];
        Promise.all([this.getRoleList(), this.getPostList()]).then(() => {
          if (this.dataForm.id) {
            this.getInfo();
          }
        });
      });
    },
    // 获取角色列表
    getRoleList() {
      return this.$http
        .post("/sys/role/list", {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then(({ data: res }) => {
          console.log("lislis", decryptECB(res.data));
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          decryptECB(res.data).then((result) => {
            let resultParse = JSON.parse(result);
            this.roleList = resultParse.data;
            // this.roleList = resultParse.data.map((item)=>{
            //   item.id = parseFloat(item.roleIdStr)
            //   return item
            // })
            console.log("roleList", this.roleList);
          });
        })
        .catch(() => {});
    },
    // 获取岗位列表
    getPostList() {
      return this.$http
        .get("/sys/post/list")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          var postlist = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].status == 1) {
              postlist.push(res.data[i]);
            }
          }
          this.postList = postlist;
        })
        .catch(() => {});
    },
    // 获取信息
    getInfo() {
      console.log("this.dataForm.id", this.dataForm.id);
      this.$http
        .post(`/sys/user/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          decryptECB(res.data).then((result) => {
            if (result) {
              let resultParse = JSON.parse(result);
              console.log("resultParse", resultParse);
              if (resultParse && resultParse.data) {
                this.dataForm = {
                  ...this.dataForm,
                  ...resultParse.data,
                  roleIdList: [],
                };
                // 角色配置, 区分是否为默认角色
                for (var i = 0; i < resultParse.data.roleIdList.length; i++) {
                  if (
                    this.roleList.filter(
                      (item) => item.roleIdStr === resultParse.data.roleIdList[i]
                    )[0]
                  ) {
                    this.dataForm.roleIdList.push(resultParse.data.roleIdList[i]);
                    continue;
                  }
                  this.roleIdListDefault.push(resultParse.data.roleIdList[i]);
                }
              }
            }
          });
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate(async (valid) => {
          if (!valid) {
            return false;
          }

          this.dataForm.id = this.dataForm.userIdStr;
          console.log("dataForm", this.dataForm);
          let params = await encryptECB(
            JSON.stringify({
              ...this.dataForm,
              roleIdList: [...this.dataForm.roleIdList, ...this.roleIdListDefault],
            })
          );
          let xSecret = await encrypt(params);
          this.$http[!this.dataForm.id ? "post" : "put"]("/sys/user", params, {
            headers: {
              "x-secret": xSecret,
              "Content-Type": "application/json",
            },
          })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>

<style lang="scss">
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
